﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;


using log4net;
using log4net.Config;
using System.Reflection;


namespace AutoRule
{
    class CTimerTaskWorker
    {
        public void Start()
        {
            _worker.Start();
        }

        public void Stop()
        {
            _WorkerStopEvent.Set();
            _worker.Join();
        }

        public static void dowork()
        {
            
  
            while (true)
            {

                //根据list中的内容 读取执行
                
                List<CTimerRule> myrulelist = CTimerRuleManager.GetInstance().Get();
                ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
                log.Info("定时开关规则：" + myrulelist.Count + "条");
                String strTime = DateTime.Now.ToString("t");
                log.Info("当前时间：" + strTime);

                foreach (CTimerRule r1 in myrulelist)
                {
                    log.Info("定时开关规则" + r1.id + ":时间 " + r1.hourTime);
                    if (r1.hourTime.Equals(strTime))
                    {
                        if (r1.weekofday.IndexOf(Week()) != -1)
                        {
                            log.Info("执行一条符合规则的定时任务");
                            if (r1.lSetInfo.Count < 1)
                            {
                                log.Warn("定时开关规则" + r1.id + ":时间 " + "无变量");
                                continue;
                            }

                            String sRequest = "action=setvars&";
                            foreach (setinfo myinfo in r1.lSetInfo)
                            {
                                
                                String sValue = "True";
                                if(myinfo.varSetValue == 0)
                                    sValue = "False";
                                sRequest += Convert.ToString(myinfo.varID) + "=" + sValue + "|";
                                CDB.GetInstance().InsertTimerLog(myinfo.varID, myinfo.varName, myinfo.varGroupName, myinfo.varSetValue);
                            }
                            sRequest = sRequest.Substring(0, sRequest.Length-1);
                            CHttpClient client = new CHttpClient();
                            log.Warn(sRequest);
                            String result = client.HttpPost("http://" + CConfig.GetInstance()._OpcSvrIp + ":" + CConfig.GetInstance()._OpcSvrPort + "/Data", sRequest);
                            log.Warn(result);
                        }
                    }
                    else
                        continue;

                }

                int nWait = 60 * 1000 - DateTime.Now.Second * 1000 - DateTime.Now.Millisecond;
                if (_WorkerStopEvent.WaitOne(nWait, true))
                    return;
            }

        }

        public string HttpGet(string Url, string postDataStr)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }

        public static string Week()
        {
            string[] weekdays = { "7", "1", "2", "3", "4", "5", "6" };
            string week = weekdays[Convert.ToInt32(DateTime.Now.DayOfWeek)];
            return week;
        }

        private static AutoResetEvent _WorkerStopEvent = new AutoResetEvent(false);
        private Thread _worker = new Thread(new ThreadStart(dowork));
    }
}
